<template>
  <div class="admin-home-content">
    <!-- 数据统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" v-loading="loading">
        <div class="stat-item">
          <div class="stat-number">{{ totalOrders }}</div>
          <div class="stat-label">总订单数</div>
          <el-icon class="stat-icon" color="#3498db"><ShoppingBag /></el-icon>
        </div>
      </el-card>
      <el-card class="stat-card" v-loading="loading">
        <div class="stat-item">
          <div class="stat-number">{{ todayOrders }}</div>
          <div class="stat-label">今日订单</div>
          <el-icon class="stat-icon" color="#e74c3c"><Calendar /></el-icon>
        </div>
      </el-card>
      <el-card class="stat-card" v-loading="loading">
        <div class="stat-item">
          <div class="stat-number">{{ productCategories }}</div>
          <div class="stat-label">商品种类</div>
          <el-icon class="stat-icon" color="#f39c12"><Box /></el-icon>
        </div>
      </el-card>
      <el-card class="stat-card" v-loading="loading">
        <div class="stat-item">
          <div class="stat-number">{{ totalUsers }}</div>
          <div class="stat-label">注册用户</div>
          <el-icon class="stat-icon" color="#27ae60"><User /></el-icon>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>订单趋势</span>
            <el-button class="button" text>查看详情</el-button>
          </div>
        </template>
        <div class="chart-placeholder">
          <div class="chart-mock" v-if="allOrders.length === 0">
            订单数据图表区域
            <br>
            (暂无订单数据，请先添加订单)
          </div>
          <div v-else class="chart-summary">
            <div class="chart-stat">
              <div class="chart-number">{{ totalOrders }}</div>
              <div class="chart-label">总订单数</div>
            </div>
            <div class="chart-stat">
              <div class="chart-number">{{ todayOrders }}</div>
              <div class="chart-label">今日订单</div>
            </div>
            <div class="chart-stat">
              <div class="chart-number">{{ allOrders.filter(o => o.status === '待处理').length }}</div>
              <div class="chart-label">待处理订单</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 最新订单表格 -->
    <div class="recent-orders">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>最新10条待处理订单</span>
            <el-button class="button" text @click="fetchDashboardData">刷新数据</el-button>
          </div>
        </template>
        <el-table :data="recentOrders" style="width: 100%" v-loading="loading">
          <el-table-column prop="orderNo" label="订单号" width="150" />
          <el-table-column prop="customer" label="收货人" width="120" />
          <el-table-column prop="status" label="订单状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row && scope.row.status" :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
              <span v-else>未知状态</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100" />
          <el-table-column prop="time" label="下单时间" width="180" />
          <el-table-column prop="category" label="订单分类" width="100" />
          <el-table-column label="操作" width="200">
            <template #default>
              <el-button size="small" type="primary" link>详情</el-button>
              <el-button size="small" type="danger" link>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="recentOrders.length === 0 && !loading" style="text-align: center; padding: 20px; color: #909399;">
          暂无待处理订单数据
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { findAllOrder } from '@/api/order'
import { findCategories } from '@/api/product'
import { getAllUserList } from '@/api/user'
import { ShoppingBag, Calendar, Box, User } from '@element-plus/icons-vue'

// 统计数据
const totalOrders = ref(0)
const todayOrders = ref(0)
const productCategories = ref(0)
const totalUsers = ref(0)

// 最近订单数据
const recentOrders = ref([])
const allOrders = ref([])
const loading = ref(false)

// 获取统计数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    // 获取所有订单
    const orderRes = await findAllOrder()
    console.log('订单API响应:', orderRes)
    
    if (orderRes.data) {
      console.log('订单数据:', orderRes.data)
      console.log('订单数量:', orderRes.data.length)
      
      allOrders.value = orderRes.data
      totalOrders.value = orderRes.data.length
      
      // 检查所有订单状态
      const allStatuses = [...new Set(orderRes.data.map(order => order.status))]
      console.log('所有订单状态值:', allStatuses)
      
      // 计算今日订单（简化处理，实际应根据具体日期判断）
      const today = new Date().toISOString().split('T')[0]
      todayOrders.value = orderRes.data.filter(order => {
        if (order.createTime) {
          return order.createTime.includes(today)
        }
        return false
      }).length
      
      // 获取最近10条待处理订单 - 扩展状态检查
      const pendingOrders = orderRes.data
        .filter(order => {
          const status = order.status
          // 扩展待处理状态的检查，包括各种可能的值
          const isPending = status === '待处理' || 
                           status === '待发货' || 
                           status === 'pending' || 
                           status === 'PENDING' ||
                           status === '待付款' ||
                           status === '已付款' ||  // 有些系统把已付款也视为待处理
                           status === '处理中' ||
                           status === 'processing' ||
                           (status && status.toString().toLowerCase().includes('待')) ||
                           (status && status.toString().toLowerCase().includes('pending'))
          
          console.log(`订单状态检查 - 状态: ${status}, 是否待处理: ${isPending}`)
          return isPending
        })
        .sort((a, b) => new Date(b.createTime || b.otime || 0) - new Date(a.createTime || a.otime || 0))
        .slice(0, 10)
      
      console.log('待处理订单数量:', pendingOrders.length)
      console.log('待处理订单详情:', pendingOrders)
      
      recentOrders.value = pendingOrders.map(order => ({
        orderNo: order.orderNo || order.onumber || '未知订单号',
        customer: order.customer || order.ousername || '未知客户',
        status: order.status || '未知状态',
        amount: order.amount || order.oamount || '0元',
        time: order.createTime || order.otime || '未知时间',
        category: order.category || '鞋靴'
      }))
      
      console.log('最终显示的待处理订单:', recentOrders.value)
    }
    
    // 获取商品分类数量
    const categoryRes = await findCategories()
    if (categoryRes.data) {
      productCategories.value = categoryRes.data.length
    }
    
    // 获取用户总数
    const userRes = await getAllUserList()
    if (userRes.data) {
      totalUsers.value = userRes.data.length
    }
    
  } catch (error) {
    console.error('获取仪表板数据失败:', error)
    console.error('错误详情:', error.message)
    console.error('错误堆栈:', error.stack)
    
    // 显示错误提示
    ElMessage.error('获取数据失败: ' + (error.message || '网络错误'))
    
    // 如果API调用失败，使用模拟数据作为后备
    useMockData()
  } finally {
    loading.value = false
  }
}

// 使用模拟数据
const useMockData = () => {
  totalOrders.value = 1248
  todayOrders.value = 156
  productCategories.value = 89
  totalUsers.value = 2345
  
  recentOrders.value = [
    {
      orderNo: '20180101234601',
      customer: '王小亮',
      status: '已付款',
      amount: '580元',
      time: '2018-01-01',
      category: '鞋靴'
    },
    {
      orderNo: '20180101234602',
      customer: '李明',
      status: '待发货',
      amount: '299元',
      time: '2018-01-01',
      category: '运动鞋'
    },
    {
      orderNo: '20180101234603',
      customer: '张三',
      status: '已发货',
      amount: '429元',
      time: '2018-01-01',
      category: '皮鞋'
    }
  ]
}

// 状态标签类型映射
const getStatusType = (status) => {
  const statusMap = {
    '已付款': 'success',
    '待发货': 'warning',
    '已发货': 'primary',
    '已完成': 'success',
    '待处理': 'warning',
    '待付款': 'warning',
    '处理中': 'primary',
    '已取消': 'danger',
    'pending': 'warning',
    'processing': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDashboardData()
})
</script>

<style scoped>
.admin-home-content {
  width: 100%;
  height: 100%;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  font-weight: 500;
}

.stat-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 24px;
  opacity: 0.3;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-placeholder {
  height: 300px;
  background: linear-gradient(45deg, #f8f9fa 25%, #e9ecef 25%, #e9ecef 50%, #f8f9fa 50%, #f8f9fa 75%, #e9ecef 75%);
  background-size: 20px 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.chart-mock {
  text-align: center;
  color: #6c757d;
  font-size: 16px;
  line-height: 1.5;
}

.recent-orders {
  margin-bottom: 20px;
}

.recent-orders .el-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #495057;
  font-weight: 600;
}

:deep(.el-button--text) {
  color: #3498db;
}

:deep(.el-button--text:hover) {
  color: #2980b9;
}

.chart-summary {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.chart-stat {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  min-width: 120px;
}

.chart-number {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 8px;
}

.chart-label {
  font-size: 14px;
  opacity: 0.9;
}
</style>